<template>
  <view>
    <button class="button" hover-class="hover" @tap="startSearch" :loading="isScanning">
      搜索蓝牙设备
    </button>
    <text class=".td">请选择名称为MHT-P28L的蓝牙设备(需授权地理位置权限)</text>
    <scroll-view class="device_list" scroll-y scroll-with-animation>
      <view v-for="(item, index) in list" :key="index" :data-title="item.deviceId" :data-name="item.name"
        :data-advertisData="item.advertisServiceUUIDs" @tap="bindViewTap" class="item" hover-class="item_hover">
        <view style="font-size: 16px; color: #333;">{{ item.name }}</view>
        <!-- <view style="font-size: 16px; color: #333;">{{ item.deviceId }}</view> -->
        <view style="font-size: 10px">
          信号强度: {{ item.RSSI }}dBm
          <!-- ({{ utils.max(0, item.RSSI + 100) }}%) -->
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
// pages/blueconn/blueconn.js
var app = getApp();

export default {
  data() {
    return {
      list: [],
      services: [],
      serviceId: 0,
      writeCharacter: false,
      readCharacter: false,
      notifyCharacter: false,
      isScanning: false
    };
  },

  components: {},
  props: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.globalData.BLEInformation.platform = app.globalData.getPlatform();
  },


  methods: {
    //搜索设备
    startSearch: function () {
      var that = this;
      uni.openBluetoothAdapter({
        success: function (res) {
          uni.getBluetoothAdapterState({
            success: function (res) {


              if (res.available) {
                if (res.discovering) {
                  uni.stopBluetoothDevicesDiscovery({
                    success: function (res) {

                    }
                  });
                } else {
                  // that.startBluetoothDevicesDiscovery()
                  that.getBluetoothDevices();
                } // that.checkPemission()
              } else {
                uni.showModal({
                  title: "提示",
                  content: "本机蓝牙不可用",
                  showCancel: false
                });
              }
            }
          });
        },
        fail: function () {
          // if (res.errCode === 10001) {
          //   wx.onBluetoothAdapterStateChange(function (res) {
          //     console.log('onBluetoothAdapterStateChange', res)
          //     if (res.available) {
          //       this.startBluetoothDevicesDiscovery()
          //     }
          //   })
          // }
          uni.showModal({
            title: "提示",
            content: "蓝牙初始化失败，请到设置打开蓝牙",
            showCancel: false
          });
        }
      });
    },
    checkPemission: function () {
      //android 6.0以上需授权地理位置权限
      var that = this;
      var platform = app.globalData.BLEInformation.platform;

      if (platform == "ios") {
        app.globalData.platform = "ios";
        that.getBluetoothDevices();
      } else if (platform == "android") {
        app.globalData.platform = "android";
        console.log(
          app.globalData
            .getSystem()
            .substring(
              app.globalData.getSystem().length - (app.globalData.getSystem().length - 8),
              app.globalData.getSystem().length - (app.globalData.getSystem().length - 8) + 1
            )
        );

        if (
          app.globalData
            .getSystem()
            .substring(
              app.globalData.getSystem().length - (app.globalData.getSystem().length - 8),
              app.globalData.getSystem().length - (app.globalData.getSystem().length - 8) + 1
            ) > 5
        ) {
          uni.getSetting({
            success: function (res) {


              if (!res.authSetting["scope.userLocation"]) {
                uni.authorize({
                  scope: "scope.userLocation",
                  complete: function (res) {
                    that.getBluetoothDevices();
                  }
                });
              } else {
                that.getBluetoothDevices();
              }
            }
          });
        }
      }
    },
    getBluetoothDevices: function () {
      //获取蓝牙设备信息
      var that = this;

      uni.showLoading({
        title: "正在加载",
        icon: "loading"
      });
      that.setData({
        isScanning: true
      });
      uni.startBluetoothDevicesDiscovery({
        success: function (res) {

          setTimeout(function () {
            uni.getBluetoothDevices({
              success: function (res) {
                var devices = [];
                var num = 0;

                for (var i = 0; i < res.devices.length; ++i) {
                  if (res.devices[i].name != "未知设备") {
                    devices[num] = res.devices[i];
                    num++;
                  }
                }

                that.setData({
                  list: devices,
                  isScanning: false
                });
                uni.hideLoading();
                uni.stopPullDownRefresh();
                // uni.stopBluetoothDevicesDiscovery({
                //   success: function (res) {
                //     uni.showModal({
                //       title: "提示",
                //       content: "搜索设备失败请重新搜索",
                //       showCancel: false
                //     });
                //   }
                // });
              }
            });
          }, 2000);
        }
      });
    },
    bindViewTap: function (e) {
      var that = this;
      uni.stopBluetoothDevicesDiscovery({
        success: function (res) {

        }
      });
      that.setData({
        serviceId: 0,
        writeCharacter: false,
        readCharacter: false,
        notifyCharacter: false
      });

      uni.showLoading({
        title: "正在连接"
      });
      uni.createBLEConnection({
        deviceId: e.currentTarget.dataset.title,
        success: function (res) {

          app.globalData.BLEInformation.deviceId = e.currentTarget.dataset.title;
          that.getSeviceId();
        },
        fail: function (e) {
          uni.showModal({
            title: "提示",
            content: "连接失败",
            showCancel: false
          });

          uni.hideLoading();
        },
        complete: function (e) {

        }
      });
    },
    getSeviceId: function () {
      var that = this;
      var platform = app.globalData.BLEInformation.platform;

      uni.getBLEDeviceServices({
        deviceId: app.globalData.BLEInformation.deviceId,
        success: function (res) {

          // if (platform == 'android') {
          //   // for(var i=0;i<res.services.length;++i){
          //   // var item = res.services[i].uuid
          //   // if (item == "0000FEE7-0000-1000-8000-00805F9B34FB"){
          //   realId = "0000FEE7-0000-1000-8000-00805F9B34FB"
          //   //       break;
          //   //     }
          //   // }
          // } else if (platform == 'ios') {
          //   // for(var i=0;i<res.services.length;++i){
          //   // var item = res.services[i].uuid
          //   // if (item == "49535343-FE7D-4AE5-8FA9-9FAFD205E455"){
          //   realId = "49535343-FE7D-4AE5-8FA9-9FAFD205E455"
          //   // break
          //   // }
          //   // }
          // }
          // app.BLEInformation.serviceId = realId

          that.setData({
            services: res.services
          });
          that.getCharacteristics();
        },
        fail: function (e) {

        },
        complete: function (e) {

        }
      });
    },
    getCharacteristics: function () {
      var that = this;
      var list = that.services;
      var num = that.serviceId;
      var write = that.writeCharacter;
      var read = that.readCharacter;
      var notify = that.notifyCharacter;
      uni.getBLEDeviceCharacteristics({
        deviceId: app.globalData.BLEInformation.deviceId,
        serviceId: list[num].uuid,
        success: function (res) {
          console.log(res);

          for (var i = 0; i < res.characteristics.length; ++i) {
            var properties = res.characteristics[i].properties;
            var item = res.characteristics[i].uuid;

            if (!notify) {
              if (properties.notify) {
                app.globalData.BLEInformation.notifyCharaterId = item;
                app.globalData.BLEInformation.notifyServiceId = list[num].uuid;
                notify = true;
              }
            }

            if (!write) {
              if (properties.write) {
                app.globalData.BLEInformation.writeCharaterId = item;
                app.globalData.BLEInformation.writeServiceId = list[num].uuid;
                write = true;
              }
            }

            if (!read) {
              if (properties.read) {
                app.globalData.BLEInformation.readCharaterId = item;
                app.globalData.BLEInformation.readServiceId = list[num].uuid;
                read = true;
              }
            }
          }

          if (!write || !notify || !read) {
            num++;
            that.setData({
              writeCharacter: write,
              readCharacter: read,
              notifyCharacter: notify,
              serviceId: num
            });

            if (num == list.length) {
              uni.showModal({
                title: "提示",
                content: "找不到该读写的特征值",
                showCancel: false
              });
            } else {
              that.getCharacteristics();
            }
          } else {
            uni.showToast({
              title: "连接成功"
            });
            that.openControl();
          }
        },
        fail: function (e) {

        },
        complete: function (e) {
          console.log("write:" + app.globalData.BLEInformation.writeCharaterId);
          console.log("read:" + app.globalData.BLEInformation.readCharaterId);
          console.log("notify:" + app.globalData.BLEInformation.notifyCharaterId);
        }
      });
    },
    openControl: function () {
      //连接成功返回主页
      uni.navigateBack({
        delta: 1,
      });
    }
  }
};
</script>
<style>
.button {
  margin-top: 20px;
  width: 90%;
  background-color: #54bec2;
  color: white;
  border-radius: 98rpx;
  background: bg_red;
}

/* 按下变颜色 */
.hover {
  background: #dcdcdc;
}

.device_list {
  height: auto;
  margin-left: 20px;
  margin-right: 20px;
  margin-top: 10px;
  margin-bottom: 20px;
  border: 1px solid #eee;
  border-radius: 5px;
  width: auto;
}

.td {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 10px;
}

/* .item {
    padding-top: 10px;
    padding-bottom: 10px;
     height: 130rpx;
     width: 100%;
} */
.item {
  display: block;
  /* font-family:  Arial, Helvetica, sans-serif;
  font-size:14px;
  margin: 0 10px;
  margin-top:10px;
  margin-bottom: 10px;
  background-color:#FFA850; 
  border-radius: 5px;
  border-bottom: 2px solid #68BAEA; */
  border-bottom: 1px solid #eee;
  padding: 4px;
  color: #666;
}

.item_hover {
  background-color: rgba(0, 0, 0, 0.1);
}

.block {
  display: block;
  color: #ffffff;
  padding: 5px;
}

/* pages/bleConnect/bleConnect.wxss */
</style>
